<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>隐写加密</title>
    <script src="imagemask.js"></script>
</head>
<body>
<input type="file" id="file">
<br>
<img src="" id="preview" alt="" style="display: none;">
<br>
<input type="text" id="message">
<br>
<button id="encode">加密</button>
<br>
<canvas id="canvas"></canvas>
</body>
</html>
<script type="text/javascript" src="imagemask.js"></script>
<script>
    var mask = new ImageMask({debug: false}); //实例化mask对象

    //加载时初始化图片加载事件以及注册点击事件
    window.onload = function() {
        //图片改变
        var input = document.getElementById('file');
        input.addEventListener('change', importImage);
        //点击事件
        var encodeButton = document.getElementById('encode');
        encodeButton.addEventListener('click', encode);
    }

    //加密
    var encode = function() {
        var message = document.getElementById('message').value; //要加密的信息
        var canvas = document.getElementById('canvas'); //获取cancas
        var preview = document.getElementById('preview'); //湖区上传图片
        var ctx = canvas.getContext('2d'); //选择canvas类型
        ctx.drawImage(preview, 0, 0, preview.width, preview.height); //根据图片宽度和高度设置画布大小
        mask.opts.debug = false; //不使用debug
        mask.hideText(canvas, message); //写入加密信息
        var data = canvas.toDataURL(); //返回data64格式图片
        openDownloadDialog(convertBase64UrlToBlob(data),"mask.png"); //弹出下载链接
    };

    //显示预览图
    var importImage = function(e) {
        var reader = new FileReader(); //文件管理器
        reader.onload = function(event) {
            document.getElementById('preview').style.display = 'block';
            document.getElementById('preview').src = event.target.result;//显示图片
            document.getElementById('message').value = ''; //清空加密信息
            var img = new Image(); //实例化image对象

            //将图片放入画布中
            img.onload = function() {
                var canvas = document.getElementById('canvas');
                var ctx = canvas.getContext('2d');
                ctx.canvas.width = img.width;
                ctx.canvas.height = img.height;
                ctx.drawImage(img, 0, 0);
            };
            img.src = event.target.result;
        };
        reader.readAsDataURL(e.target.files[0]); //返回将图片内容填入以显示图片
    };

    /**
     * 将以base64的图片url数据转换为Blob
     * @param urlData
     *用url方式表示的base64图片数据
     */
    function convertBase64UrlToBlob(urlData){

        var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte

        //处理异常,将ascii码小于0的转换为大于0
        var ab = new ArrayBuffer(bytes.length);
        var ia = new Uint8Array(ab);
        for (var i = 0; i < bytes.length; i++) {
            ia[i] = bytes.charCodeAt(i);
        }
        return new Blob( [ab] , {type : 'image/png'});
    }

    /**
     * 通用的打开下载对话框方法，没有测试过具体兼容性
     * @param url 下载地址，也可以是一个blob对象，必选
     * @param saveName 保存文件名，可选
     */
    function openDownloadDialog(url, saveName)
    {
        if(typeof url == 'object' && url instanceof Blob)
        {
            url = URL.createObjectURL(url); // 创建blob地址
        }
        var aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        var event;
        if(window.MouseEvent) event = new MouseEvent('click');
        else
        {
            event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
    }
</script>